var _columns = [{
        checkbox: true
    },
    {
        field: 'ID',
        title: 'id',
        sortable: true
    },
    {
        title: '序号',
        field: 'showId',
        formatter: function (value, row, index) {
            return index + 1;
        }
    },
    {
        field: 'SENSOR_ROW_ID',
        title: '设备编号',
        sortable: true
    },
    {
        field: 'SENSOR_TYPE',
        title: '设备类型',
        sortable: false
    },
    {
        field: "WORKSHOP",
        title: '所在位置',
        sortable: true
    },
    {
        field: 'CREATED_AT',
        title: '最新采集时间',
        sortable: true
    },

    {
        field: 'OPERATOR',
        title: '录入人员',
        sortable: true
    },
    {
        field: 'VALUE',
        title: '采集数值',
        sortable: true
    },
    {
        field: 'operation',
        title: '操作',
        formatter: function (value, row, index) {
            var e = '<a id="hello" href="#" mce_href="#" onclick="edit(\'' + row.SENSOR_ROW_ID + '\')"><i class="fa fa-edit" ></i>详情</a>';
            $("#hello").innerHTML = row.SENSOR_ROW_ID
            return e;
        }
    },
]

var selected_id = ''


var TableInit = function () {
    var oTableInit = new Object();
    //初始化Table
    oTableInit.Init = function () {
        $('#data_table').bootstrapTable({
            url: '/entity_water/selectall_by_companyid_and_search', //请求后台的URL（*）
            method: 'get', //请求方式（*）
            toolbar: '#toolbar', //工具按钮用哪个容器
            cache: false, //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true, //是否显示分页（*）
            queryParams: oTableInit.queryParams, //传递参数（*）
            sidePagination: "server", //分页方式：client客户端分页，server服务端分页（*）
            pageNumber: 1, //初始化加载第一页，默认第一页
            pageSize: 10, //每页的记录行数（*）
            pageList: [10, 25, 50, 100], //可供选择的每页的行数（*）
            showColumns: true, //是否显示所有的列
            showRefresh: true, //是否显示刷新按钮
            clickToSelect: true, //是否启用点击选中行
            uniqueId: "ID", //每一行的唯一标识，一般为主键列
            sortable: true, //是否启用排序
            sortOrder: "desc",
            columns: _columns,
            showExport: true, //是否显示导出按钮
            exportTypes: ['csv', 'doc', 'excel'], //['csv', 'txt', 'sql', 'doc', 'excel', 'xlsx', 'pdf'],           //导出文件类型
            exportDataType: "basic", //basic当前页', 'all所有, 'selected'.
            exportOptions: {
                fileName: '实体水信息管理', //文件名称设置
                excelstyles: ['background-color', 'color', 'font-size', 'font-weight']
            },
        });

    };
    //得到查询的参数
    oTableInit.queryParams = function (params) {
        var temp = { //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            limit: params.limit, //页面大小
            page: (params.offset / params.limit) + 1,//页码
            company_id: "" + label_id,
            sensor_row_id: sensor_row_id,
            searchContent: '-',
        };
        return temp;
    };
    return oTableInit;
};
var ButtonInit = function () {
    var oInit = new Object();

    oInit.Init = function () {

        /**
         * 数据迁移前端按钮
         */
        $("#btn_reload").click(function () {
            $.ajax({
                type: "get",
                url: "/entity_water/data_collection",
                async:false,
                success: function(data) {
//                       console.log(data)
                }
            })
        })

        //初始化页面上面的按钮事件
        //新增按钮
        $("#btn_return").click(function () {
            $('#page-wrapper').load('pages/technological_process.html');
        })

        $("#btn_add").click(function () {
            $('#sensorid').val("");
            $('#sort').empty();
            $('#newVALUE').val("");
            $('#newCREATED_AT').val(getNowFormatDate());
            $('#newCREATED_AT').datetimepicker({
                format: "yyyy-mm-dd hh:ii:ss",
                language: 'zh-CN',
                todayBtn: true,
                autoclose: true,
                todayHighlight: 1,
                startView: 2,
                showMeridian: true,
                endDate: new Date(),
            });
            getNewWorkShop()
            getSelectType()
            getSelectNo()
            $('#sort').change(function () {
                getSelectNo()
            });
            $('#workshop').change(function () {
                getSelectType()
                getSelectNo()
            });
            $('#new_data').modal()
        });

        //编辑按钮
        $("#btn_edit").click(function () {
            var arrselections = $("#data_table").bootstrapTable('getSelections');

            if (arrselections.length > 1) {
                bootoast({
                    message: '只能选择一行进行编辑',
                    position: 'top',
                    type: 'warning',
                    timeout: 1.5,
                });
                return;
            }
            if (arrselections.length <= 0) {
                bootoast({
                    message: '请选择有效数据',
                    position: 'top',
                    type: 'warning',
                    timeout: 1.5,
                });
                return;
            }
            $('#editCREATED_AT').datetimepicker({
                format: "yyyy-mm-dd hh:ii:ss",
                language: 'zh-CN',
                todayBtn: true,
                autoclose: true,
                todayHighlight: 1,
                startView: 2,
                showMeridian: true,
                endDate: new Date(),
            });
            selected_id = arrselections[0].ID
            //获取所有所在位置
            $.ajax({
                type: 'get',
                url: '/chart/queryLocationByBusinessId',
                data: {
                    'businessId': label_id
                },
                dataType: 'json',
                async: false,
                contentType: "application/json; charset=utf-8",
                success: function (res) {
                    let data = res.data
                    $('#editworkshop').empty();
                    for (var i = 0; i < data.length; i++) {
                        $("#editworkshop").append(
                            "<option value='" + data[i] + "'>" + data[i] +
                            "</option>");
                    }
                    $("#editworkshop").val(arrselections[0].WORKSHOP)
                },
            });
            //获取设备类型
            $.ajax({
                type: 'get',
                url: '/chart/querySensorTypeByLocation',
                data: {
                    'businessId': label_id,
                    'location': arrselections[0].WORKSHOP,
                },
                dataType: 'json',
                async: false,
                contentType: "application/json; charset=utf-8",
                success: function (res) {
                    let data = res.data
                    $('#editsort').empty();
                    for (var i = 0; i < data.length; i++) {
                        $("#editsort").append(
                            "<option value='" + data[i] + "'>" + data[i] +
                            "</option>");
                    }
                    $("#editsort").val(arrselections[0].SENSOR_TYPE)
                },
            });
            //获取设备编号
            $.ajax({
                type: 'get',
                url: '/chart/querySensorIdByLocationAndType',
                data: {
                    'businessId': label_id,
                    'location': $("#editworkshop").val(),
                    'sensorType': $("#editsort").val(),
                },
                dataType: 'json',
                async: false,
                contentType: "application/json; charset=utf-8",
                success: function (res) {
                    let data = res.data
                    $('#editsensorid').empty();
                    for (var i = 0; i < data.length; i++) {
                        $("#editsensorid").append(
                            "<option value='" + data[i] + "'>" + data[i] +
                            "</option>");
                    }
                    $('#editsensorId').val(arrselections[0].SENSOR_ROW_ID)
                },
            });
            $('#editCREATED_AT').val(arrselections[0].CREATED_AT);
            $('#editSENSOR_ROW_ID').val(arrselections[0][_columns[4].field]);
            $('#editVALUE').val(arrselections[0][_columns[6].field]);
            $("#editVALUE").val(arrselections[0].VALUE)
            $('#editworkshop').change(function () {
                getEditSensorType()
            });

            $('#editsort').change(function () {
                getEditSensorRowId()
            });
            $('#edit_data').modal();
        });

        // 删除按钮
        $("#btn_delete").click(function () {
            var arrselections = $("#data_table").bootstrapTable('getSelections');
            if (arrselections.length <= 0) {
                bootoast({
                    message: '请选择有效数据',
                    position: 'top',
                    type: 'warning',
                    timeout: 1.5,
                });
                return;
            }

            let values = [];
            for (var i = 0; i < arrselections.length; i++)
                values.push(arrselections[i].ID);

            bootbox.confirm({
                message: "确认要删除选择的数据吗？",
                locale: 'zh_CN',
                title: '操作提示',
                callback: function (result) {
                    if (result) {
                        $.ajax({
                            type: "post",
                            url: "/entity_water/delete",
                            data: JSON.stringify(values),
                            contentType: "application/json",
                            success: function (data) {
                                if (data['status'] == "success") {
                                    bootoast({
                                        message: '删除成功',
                                        position: 'top',
                                        type: 'success',
                                        timeout: 1.5,
                                    });
                                    $("#data_table").bootstrapTable('refresh');
                                } else {
                                    bootoast({
                                        message: '删除失败\n' + data['msg'],
                                        position: 'top',
                                        type: 'danger',
                                        timeout: 1.5,
                                    });
                                }
                            }
                        });
                    }
                }
            })

        });

        //新增框内的提交
        $('#new_data_submit').on('click', function () {
            var createdAt = $('#newCREATED_AT').val();
            var sensorRowId = $('#sensorid').val();
            var value = $('#newVALUE').val();
            var sensortype = $('#sort').val()
            //            let location = $('#location').val()
            let workshop = $('#workshop').val()
            fieldIsEmpty(sensorRowId, "设备编号不能为空", '');
            if (isNaN(Number(value))) //数值不等于NaN,Number转化为数字类型，isNaN是否为NaN
            {
                bootoast({
                    message: '值请输入数字类型',
                    position: 'top',
                    type: 'danger',
                    timeout: 2,
                });
                return;
            }
            if (value == "") {
                bootoast({
                    message: '请输入值',
                    position: 'top',
                    type: 'warning',
                    timeout: 1.5,
                });
                return;
            }

            $.ajax({
                type: "post",
                url: "/entity_water/insert",
                contentType: "application/json",
                data: JSON.stringify({
                    'createdAt': createdAt,
                    'sensorRowId': sensorRowId,
                    'value': value,
                    'companyId': label_id,
                    'sensorType': sensortype,
                    'workshop': workshop,
                }),
                success: function (data) {
                    if (data['status'] == "success") {
                        bootoast({
                            message: '插入成功',
                            position: 'top',
                            type: 'success',
                            timeout: 2,
                        });
                        $("#new_data").modal('hide');
                        $('#newCREATED_AT').val("");
                        $('#sensorid').val("");
                        $('#newVALUE').val("");
                        $('#workshop').val("");
                        $('#sort').val("");
                        $("#data_table").bootstrapTable('refresh');
                    } else {
                        bootoast({
                            message: '插入失败\n' + data['msg'],
                            position: 'top',
                            type: 'danger',
                            timeout: 2,
                        });
                    }
                },
                /*error: function () {
                    bootoast({
                        message: '通讯异常',
                        position: 'top',
                        type: 'danger',
                        timeout: 1.5,
                    });
                }*/
            });
        });

        $("#upload").click(function () {
            var formData = new FormData($('#uploadForm')[0]);
            formData.append("companyId", label_id);

            $.ajax({
                type: 'post',
                url: "/entity_water/import",
                data: formData,
                cache: false,
                processData: false,
                contentType: false,
            }).success(function (data) {
                $("#data_table").bootstrapTable('refresh');
            }).error(function () {
                alert("上传失败");
            });
            $("#upload_file").modal('hide');
        });

        $("#btn_import").click(function () {
            $('#upload_file').modal();
        })

        //编辑框内的提交
        $('#edit_data_submit').on('click', function () {

            var arrselections = $("#data_table").bootstrapTable('getSelections');
            var createdAt = $('#editCREATED_AT').val();
            var sensorRowId = $('#editsensorid').val();
            var value = $('#editVALUE').val();
            var sensortype = $('#editsort').val()
            //            let location = $('#edit').val()
            let workshop = $('#editworkshop').val()
            fieldIsEmpty(sensorRowId, "设备编号不能为空", '');
            if (isNaN(Number(value))) //数值不等于NaN,Number转化为数字类型，isNaN是否为NaN
            {
                bootoast({
                    message: '值请输入数字类型',
                    position: 'top',
                    type: 'danger',
                    timeout: 2,
                });
                return;
            }
            if (value == "") {
                bootoast({
                    message: '请输入值',
                    position: 'top',
                    type: 'warning',
                    timeout: 1.5,
                });
                return;
            }

            $.ajax({
                type: "post",
                url: "/entity_water/update",
                contentType: "application/json",
                data: JSON.stringify({
                    'createdAt': createdAt,
                    'sensorRowId': sensorRowId,
                    'value': value,
                    'companyId': label_id,
                    'sensorType': sensortype,
                    'workshop': workshop,
                    'id': selected_id,
                }),
                success: function (data) {
                    if (data['status'] == "success") {
                        bootoast({
                            message: '修改成功',
                            position: 'top',
                            type: 'success',
                            timeout: 2,
                        });
                        $("#edit_data").modal('hide');
                        $('#newCREATED_AT').val("");
                        $('#sensorid').val("");
                        $('#newVALUE').val("");
                        $('#workshop').val("");
                        $('#sort').val("");
                        $("#data_table").bootstrapTable('refresh');
                    } else {
                        bootoast({
                            message: '插入失败\n' + data['msg'],
                            position: 'top',
                            type: 'danger',
                            timeout: 2,
                        });
                    }
                },
                /*error: function () {
                    bootoast({
                        message: '通讯异常',
                        position: 'top',
                        type: 'danger',
                        timeout: 1.5,
                    });
                }*/
            });
        });

        //搜索按钮
        $('#btn_search').click(function () {
            $('#search_content').val("");
            $('#search_data').modal();
            //$('#data_table').bootstrapTable('remove', {field: 'companyName', values: str})
        });

        //搜索框提交
        //搜索框内的提交
        $('#search_data_submit').click(function() {
            var ids = [];
            var searchContent = $('#search_content').val();
            console.log(searchContent)

            var queryParam = function (params) {
                var temp = { //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
                    limit: params.limit, //页面大小
                    page: (params.offset / params.limit) + 1,//页码
                    company_id: "" + label_id,
                    sensor_row_id: sensor_row_id,
                    searchContent: searchContent,
                };
                return temp;
            };
            $('#data_table').bootstrapTable('destroy').bootstrapTable({
                url: '/entity_water/selectall_by_companyid_and_search', //请求后台的URL（*）
                method: 'get', //请求方式（*）
                toolbar: '#toolbar', //工具按钮用哪个容器
                cache: false, //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                pagination: true, //是否显示分页（*）
                queryParams: queryParam, //传递参数（*）
                sidePagination: "server", //分页方式：client客户端分页，server服务端分页（*）
                pageNumber: 1, //初始化加载第一页，默认第一页
                pageSize: 10, //每页的记录行数（*）
                pageList: [10, 25, 50, 100], //可供选择的每页的行数（*）
                showColumns: true, //是否显示所有的列
                showRefresh: true, //是否显示刷新按钮
                clickToSelect: true, //是否启用点击选中行
                uniqueId: "ID", //每一行的唯一标识，一般为主键列
                sortable: true, //是否启用排序
                sortOrder: "desc",
                columns: _columns,
                showExport: true, //是否显示导出按钮
                exportTypes: ['csv', 'doc', 'excel'], //['csv', 'txt', 'sql', 'doc', 'excel', 'xlsx', 'pdf'],           //导出文件类型
                exportDataType: "basic", //basic当前页', 'all所有, 'selected'.
                exportOptions: {
                    fileName: '实体水信息管理', //文件名称设置
                    excelstyles: ['background-color', 'color', 'font-size', 'font-weight']
                },
            });
            $('#data_table').bootstrapTable('hideColumn', 'ID');
            $('#search_data').modal('hide');
        });


    };

    return oInit;
};

function hasPermission() {
    queryPermission('水信息管理/数据采集/水信息', '批量导入', 'btn_import')
    queryPermission('水信息管理/数据采集/水信息', '新增', 'btn_add')
    queryPermission('水信息管理/数据采集/水信息', '编辑', 'btn_edit')
    queryPermission('水信息管理/数据采集/水信息', '删除', 'btn_delete')
}

$(function () {

    hasPermission()

    //1.初始化Table
    var oTable = new TableInit();
    oTable.Init();

    //2.初始化Button的点击事件
    var oButtonInit = new ButtonInit();
    oButtonInit.Init();

    $('#data_table').bootstrapTable('hideColumn', 'ID');

});

function refreshSort() {
    var arrselections = $("#data_table").bootstrapTable('getSelections');
    //清除之前缓存数据
    $('#editsort').empty();
    $('#editsensorid').empty();
    var workshop = $("#editworkshop").val();
    workshop = "workshop=" + workshop;
    //根据车间查类型
    $.ajax({
        type: 'get',
        url: '/warning_record/querysortbyworkshop?' + workshop,
        async: false,
        success: function (data) {
            for (var i = 0; i < data.length; i++) {
                $("#editsort").append(
                    "<option value='" + data[i] + "'>" +
                    data[i] + "</option>");
            }
            $("#editsort").trigger("change");
        }
    });
    $('#edit_data').modal();
}

function refreshSensorId(sensor_row_id) {
    //清除之前缓存数据
    $('#editsensorid').empty();
    var workshop = $("#editworkshop").val();
    workshop = "workshop=" + workshop;
    var sort = $("#editsort").val();
    sort = "sort=" + sort;

    //根据车间和类型查传感器编号
    $.ajax({
        type: 'get',
        url: '/warning_record/querysensorrowidbyworkshopandsort?' + workshop + '&' + sort,
        async: false,
        success: function (data) {
            for (var i = 0; i < data.length; i++) {
                $("#editsensorid").append(
                    "<option value='" + data[i] + "'>" +
                    data[i] + "</option>");
            }
            $("#editsensorid").val(sensor_row_id)
        }
    });
}
//小函数
//获取当前时期 yyyy-mm-dd hh:mm:ss
function getNowFormatDate() {
    var date = new Date();
    var seperator1 = "-";
    var seperator2 = ":";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    var Hours = date.getHours();
    var Minutes = date.getMinutes();
    var Seconds = date.getSeconds();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    if (Hours >= 0 && Hours <= 9) {
        Hours = "0" + Hours;
    }
    if (Minutes >= 0 && Minutes <= 9) {
        Minutes = "0" + Minutes;
    }
    if (Seconds >= 0 && Seconds <= 9) {
        Seconds = "0" + Seconds;
    }
    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate +
        " " + Hours + seperator2 + Minutes +
        seperator2 + Seconds;
    return currentdate;
}

var business_id;
var sensor_row_id;

function edit(id) {
    business_id = label_id;
    sensor_row_id = id;
    $('#page-wrapper').load("pages/entity_water_child.html");
}

function upload() {
    $("#fileUpload").on("change", function () {
        var obj = document.getElementById("fileUpload");
        var files = obj.files;
        var formData_file = new FormData();
        formData_file.append("file", files[0]);

        /*$.axios.post("declare/collaborative-info/uploadFile", fd).then(res => {
            if (res.code == "0") {
                this.$message.success("保存成功")
                this.findTableData();
                this.fileList = [];
                this.file = null;
                this.uploadApplyVisible = false
            } else {
                this.$message.error("保存失败 " + res.message)
            }
        })*/



        $.ajax({
            type: "post",
            url: "/entity_water/import",
            //contentType: "application/vnd.ms-excel",
            contentType: "multipart/form-data",
            processData: false,
            data: formData_file,
            dataType: 'json',
            add: function (e, data) {
                var goUpload = true;
                var uploadFile = data.files[0];
                if (files.size > 2000000) { // 2mb
                    alert('上传文件大小不得超过2M');
                    goUpload = false;
                }
                if (goUpload == true) {
                    data.submit();
                }
            },
            done: function (e, data) {
                bootoast({
                    message: '上传成功\n' + data['msg'],
                    position: 'top',
                    type: 'success',
                    timeout: 1.5,
                });
            }
        });
    })
}

function getSelectType() {
    $.ajax({
        type: 'get',
        url: '/chart/querySensorTypeByLocation',
        data: {
            'businessId': label_id,
            'location': $("#workshop").val()
        },
        dataType: 'json',
        async: false,
        contentType: "application/json; charset=utf-8",
        success: function (res) {

            let data = res.data

            $('#sort').empty();
            for (var i = 0; i < data.length; i++) {
                $("#sort").append(
                    "<option value='" + data[i] + "'>" + data[i] +
                    "</option>");
            }
        },
    });
}

function getSelectNo() {
    $.ajax({
        type: 'get',
        url: '/chart/querySensorIdByLocationAndType',
        data: {
            'businessId': label_id,
            'location': $("#workshop").val(),
            'sensorType': $("#sort").val(),
        },
        dataType: 'json',
        async: false,
        contentType: "application/json; charset=utf-8",
        success: function (res) {

            let data = res.data
            $('#sensorid').empty();
            for (var i = 0; i < data.length; i++) {
                $("#sensorid").append(
                    "<option value='" + data[i] + "'>" + data[i] +
                    "</option>");
            }
            $("#sensorid").trigger("change")
        },
    });
}

function getNewWorkShop() {
    $.ajax({
        type: 'get',
        url: '/chart/queryLocationByBusinessId',
        data: {
            'businessId': label_id
        },
        dataType: 'json',
        async: false,
        contentType: "application/json; charset=utf-8",
        success: function (res) {
            let data = res.data
            $('#workshop').empty();
            for (var i = 0; i < data.length; i++) {
                $("#workshop").append(
                    "<option value='" + data[i] + "'>" + data[i] +
                    "</option>");
            }

        },
    });
}

function getEditWorkShop() {
    $.ajax({
        type: 'get',
        url: '/chart/queryLocationByBusinessId',
        data: {
            'businessId': label_id
        },
        dataType: 'json',
        async: false,
        contentType: "application/json; charset=utf-8",
        success: function (res) {
            let data = res.data
            $('#editworkshop').empty();
            for (var i = 0; i < data.length; i++) {
                $("#editworkshop").append(
                    "<option value='" + data[i] + "'>" + data[i] +
                    "</option>");
            }
        },
    });
}

function getEditSensorType() {
    $.ajax({
        type: 'get',
        url: '/chart/querySensorTypeByLocation',
        data: {
            'businessId': label_id,
            'location': $("#editworkshop").val()
        },
        dataType: 'json',
        async: false,
        contentType: "application/json; charset=utf-8",
        success: function (res) {
            let data = res.data
            $('#editsort').empty();
            for (var i = 0; i < data.length; i++) {
                $("#editsort").append(
                    "<option value='" + data[i] + "'>" + data[i] +
                    "</option>");
            }
            getEditSensorRowId()
        },
    });
}

function getEditSensorRowId() {
    $.ajax({
        type: 'get',
        url: '/chart/querySensorIdByLocationAndType',
        data: {
            'businessId': label_id,
            'location': $("#editworkshop").val(),
            'sensorType': $("#editsort").val(),
        },
        dataType: 'json',
        async: false,
        contentType: "application/json; charset=utf-8",
        success: function (res) {
            let data = res.data
            $('#editsensorid').empty();
            for (var i = 0; i < data.length; i++) {
                $("#editsensorid").append(
                    "<option value='" + data[i] + "'>" + data[i] +
                    "</option>");
            }
        },
    });
}